package org.server.http;

import java.io.IOException;
import java.io.OutputStream;

import org.server.http.core.HttpRequest;
import org.server.http.core.HttpResponse;

/**
 * servlet父类
 * 
 * @author Admin
 * 
 */
public abstract class Servlet {

	/**
	 * 处理get请求
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public abstract void get(HttpRequest request, HttpResponse response) throws IOException;

	/**
	 * 处理post请求
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public abstract void post(HttpRequest request, HttpResponse response) throws IOException;

	/**
	 * 输出字节流数据响应到客户端
	 * 
	 * @param data
	 * @throws IOException
	 */
	public void output(HttpResponse response, byte[] data) throws IOException {
		if (data == null) {
			// 避免空空指针异常
			data = new byte[0];
		}
		// 设置状态码
		response.setStatus(200);
		OutputStream out = response.getOutputStream();
		out.write(data);
		out.flush();
	}

	/**
	 * 输出字符串到客户端
	 * 
	 * @param response
	 * @param data
	 * @throws IOException
	 */
	public void output(HttpResponse response, String data) throws IOException {
		if (data == null) {
			// 避免空空指针异常
			data = "";
		}
		output(response, data.getBytes("UTF-8"));
	}
}
